package cn.angis.system.service;

import cn.angis.common.constant.Constant;
import cn.angis.common.util.TreeUtil;
import cn.angis.db.service.BaseService;
import cn.angis.system.model.Resource;
import cn.angis.system.model.Roleres;
import cn.dev33.satoken.stp.StpUtil;
import org.noear.solon.annotation.ProxyComponent;
import org.noear.solon.data.annotation.Cache;
import org.sagacity.sqltoy.model.EntityQuery;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 资源表服务
* @author angis.cn
* @Date 2023-01-05
*/
@ProxyComponent
public class ResourceService extends BaseService<Resource> {
    /**
     * 根据用户id获取资源权限列表
     * @param userId
     * @return: List<String>
     * @throws: 
     * @Date: 2023/1/8     
     */
    @Cache
    public List<String> selectResourcesCodeByUserId(String userId) {
        return dao.findBySql("selectResourcesCodeByUserId", Map.of("userId", userId), String.class);
    }

    @Cache
    public List<Resource> listByUserId() {
        String userId = StpUtil.getLoginId("");
        return TreeUtil.listToTree(dao.findBySql("listByUserId", Map.of("userId", userId), Resource.class));
    }

    @Cache
    public List<Resource> getRouterList() {
        return dao.findEntity(Resource.class, EntityQuery.create().select("permission", "route_path", "http_method")
                .where("permission is not null and route_path is not null and http_method is not null and res_status='0'")
                .orderBy("res_sort"));
    }

    public List<Resource> getResourceTreeList() {
        return TreeUtil.listToTree(dao.findEntity(Resource.class, EntityQuery.create().orderBy("res_sort")));
    }

    @Cache
    public List<Resource> getMenuList() {
        List<Resource> resourceList = dao.findEntity(Resource.class, EntityQuery.create().select("label", "value")
                .where("#[type in (:types)]")
                .values(List.of(Constant.DISABLE, Constant.MENU)).orderBy("res_sort"));
        return TreeUtil.listToTree(resourceList);
    }

    public List<String> getResourceIdListByRoleId(String roleId) {
        return dao.findEntity(Roleres.class, EntityQuery.create()
                .where("#[roleId=:roleId]")
                .values(roleId)).stream().map(Roleres::getResId)
                .collect(Collectors.toList());
    }
}